<?php
declare (strict_types=1);

namespace magein\sms\service\laravel;

use Illuminate\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use magein\sms\Send;
use magein\sms\SmsException;

class SmsController
{
    /**
     * @var Application
     */
    protected $app;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var Send
     */
    protected $send = null;

    /**
     * @param Request $request
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function __construct(Request $request)
    {
        $this->app = app();
        $this->request = $request;
        $this->send = $this->app->get('sms')->send;
    }

    /**
     * @return JsonResponse
     */
    public function code(): JsonResponse
    {
        $data = $this->request->post();

        try {
            $result = $this->send->code($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return response()->json($result->toArray());
    }

    /**
     * @return JsonResponse
     */
    public function message(): JsonResponse
    {
        $data = $this->request->post();

        try {
            $result = $this->send->message($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return response()->json($result->toArray());
    }

    /**
     * @return JsonResponse
     */
    public function batch(): JsonResponse
    {
        $data = $this->request->post();

        try {
            $result = $this->send->batch($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return response()->json($result->toArray());
    }

    /**
     * @return JsonResponse
     */
    public function delay(): JsonResponse
    {
        $data = $this->request->post();

        try {
            $result = $this->send->delay($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return response()->json($result->toArray());
    }
}
